﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using SD.Business;
using SD.Web.Controls;
using SD.DataAccess;

namespace SD.Web.Org
{
    /// <summary>
    /// Add Organization class
    /// </summary>
    public partial class OrganizationDetails : Page
    {
        #region Events

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadCountries();
                LoadReferenceData();
                LoadOrganisation();
                LoadOrganisationPrograms();
            }

            //LoadSupportingMaterialFrame();
            //LoadDirectorateFrame();
            InitPostBackControlValues();
        }

        /// <summary>
        /// Catch event from AddressLookup for binding data to control 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void AddressLookupPopup_SelectedValue(object sender, Controls.Lookup.SelectedValueEventArgs e)
        {
            HiddenFieldAddressId.Value = e.Address.AddressId.ToString();
            TextBoxAddressLine1.Text = e.Address.AddressLine;
            TextBoxAddressLine2.Text = e.Address.AddressLine2;
            TextBoxAddressLine3.Text = e.Address.AddressLine3;
            TextBoxPostcode.Text = e.Address.Postcode;
        }

        /// <summary>
        /// Catch event from AddressLookup to reset control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void AddressLookupPopup_ClickedNoneButton(object sender, EventArgs e)
        {
            TextBoxAddressLine1.Text = "";
            TextBoxAddressLine2.Text = "";
            TextBoxAddressLine3.Text = "";
            TextBoxPostcode.Text = "";
        }

        /// <summary>
        /// Handles the Command event of the ButtonLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonLookup_Command(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "contact":
                    ContactLookupPopup.Popup();
                    break;

                case "postcode":
                    AddressLookupPopup.Popup();
                    break;

                case "business":
                    BusinessLookup.Popup();
                    break;
            }
        }

        /// <summary>
        /// Handles the Click event of the ButtonSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonSave_Command(object sender, CommandEventArgs e)
        {
            // Initialize Organization object
            var organization = new Organization();
            organization.OrganizationName = TextBoxOrganizationName.Text;


            // Check is name exists
            if (!organization.OrganizationName.Equals(HiddenFieldOrganizationName.Value) &&
                OrganizationBO.IsNameExists(organization.OrganizationName))
            {
                LabelNameExists.Text = "Organization name must be unique";
                return;
            }

            // Assign other value to the object properties
            if (ButtonSave.CommandName.Equals("edit"))
            {
                int organizationId;
                organization.OrganizationId = int.TryParse(HiddenFieldOrganizationId.Value, out organizationId)
                                                  ? organizationId
                                                  : 0;
            }


            organization.ShortDescription = TextBoxShortDescription.Text;
            organization.FullDescription = TextBoxFullDescription.Text;
            organization.CityTown = TextBoxCityTown.Text;
            organization.County = TextBoxCounty.Text;
            organization.PreferredOrganization = CheckBoxPreferredOrganization.Checked;
            organization.PhoneNumber = TextBoxPhoneNumber.Text;
            organization.Fax = TextBoxFax.Text;
            organization.Email = TextBoxEmail.Text;
            organization.WebAddress = TextBoxWebAddress.Text;
            organization.CharityNumber = TextBoxCharityNumber.Text;
            organization.CompanyNumber = TextBoxCompanyNumber.Text;
            organization.CountryId = DropDownListNationCounty.SelectedValue;

            // Hidden fields
            int contactId;
            organization.ContactId = int.TryParse(HiddenFieldContactId.Value, NumberStyles.Integer,
                                                  CultureInfo.CurrentCulture, out contactId)
                                         ? contactId
                                         : (int?) null;
            organization.BusinessId = int.Parse(HiddenFieldBusinessId.Value, CultureInfo.CurrentCulture);
            organization.AddressId = int.Parse(HiddenFieldAddressId.Value, CultureInfo.CurrentCulture);

            // Reference details
            string specialism = string.Join("-",
                                            CheckBoxListOrgSpecial.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                                                c => c.Value));
            string disabilities = string.Join("-",
                                              CheckBoxListDisabilities.Items.Cast<ListItem>().Where(c => c.Selected).
                                                  Select(c => c.Value));
            string barriers = string.Join("-",
                                          CheckBoxListBarriers.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                                              c => c.Value));
            string benefits = string.Join("-",
                                          CheckBoxListBenefits.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                                              c => c.Value));
            string circumstances = string.Join("-",
                                               CheckBoxListCircumstances.Items.Cast<ListItem>().Where(c => c.Selected).
                                                   Select(c => c.Value));
            string ethnicity = string.Join("-",
                                           CheckBoxListEthnicity.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                                               c => c.Value));
            string accreditation = string.Join("-",
                                               CheckBoxListAccreditation.Items.Cast<ListItem>().Where(c => c.Selected).
                                                   Select(c => c.Value));
            organization.OrganizationSpecialism = specialism;
            organization.ServiceDisabilities = disabilities;
            organization.ServiceBarriers = barriers;
            organization.ServiceBenefits = benefits;
            organization.ServiceCircumstances = circumstances;
            organization.ServiceEthnicity = ethnicity;
            organization.Accreditation = accreditation;
            organization.IsActive = true;

            bool savedResult = ButtonSave.CommandName.Equals("new")
                                   ? OrganizationBO.AddOrganization(organization)
                                   : OrganizationBO.EditOrganization(organization);

            // Add Organization
            if (!savedResult)
            {
                DialogBox.Error("Save Organization failed");
                return;
            }

            // Expression of Interest
            if (CheckBoxInterest.Checked)
            {
                List<OrganizationProgram> organisationPrograms =
                    CheckBoxListPrograms.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                        c =>
                        new OrganizationProgram
                            {OrganizationId = organization.OrganizationId, ProgramId = Convert.ToInt32(c.Value, CultureInfo.CurrentCulture)}).ToList
                        ();
                if (ButtonSave.CommandName.Equals("new"))
                {
                    OrganizationBO.AddOrganizationProgram(organisationPrograms);
                }
                else
                {
                    OrganizationBO.EditOrganizationProgram(organization.OrganizationId, organisationPrograms);
                }
            }

            // Set the control values after add Organization
            ButtonSave.CommandName = "edit";
            ButtonInactive.Visible = true;
            HiddenFieldOrganizationId.Value = organization.OrganizationId.ToString(CultureInfo.CurrentCulture);
            HiddenFieldOrganizationName.Value = organization.OrganizationName;

            //LoadDirectorateFrame();
            //LoadSupportingMaterialFrame();

            // Show inform message to screen
            DialogBox.Success("Save Organization successfully.");
        }

        /// <summary>
        /// Handles the CheckedChanged event of the CheckBoxInterest control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CheckBoxInterest_CheckedChanged(object sender, EventArgs e)
        {
            LinkDetails03.Visible = CheckBoxInterest.Checked;
            DetailsPanel03.Visible = CheckBoxInterest.Checked;
            LoadExpressionOfInterest();
        }

        /// <summary>
        /// Handles the Command event of the ButtonInactive control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonInactive_Command(object sender, CommandEventArgs e)
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganizationId.Value, out organisationId))
            {
                OrganizationBO.SetOrganizationStatus(organisationId, false);
                ButtonInactive.Visible = false;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Loads the edited Organization.
        /// </summary>
        private void LoadOrganisation()
        {
            int organisationId;
            if (!int.TryParse(Request.Params["id"], out organisationId))
            {
                return;
            }

            Organization organisation = OrganizationBO.GetOrganizationById(organisationId);
            if (organisation != null)
            {
                TextBoxOrganizationName.Text = organisation.OrganizationName;
                TextBoxShortDescription.Text = organisation.ShortDescription;
                TextBoxFullDescription.Text = organisation.FullDescription;
                if (organisation.Contact != null)
                {
                    TextBoxLeadContact.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}",
                                                            organisation.Contact.FirstName,
                                                            organisation.Contact.Surname);
                }

                TextBoxAddressLine1.Text = organisation.Address.AddressLine;
                TextBoxAddressLine2.Text = organisation.Address.AddressLine2;
                TextBoxAddressLine3.Text = organisation.Address.AddressLine3;
                TextBoxPostcode.Text = organisation.Address.Postcode;
                TextBoxCityTown.Text = organisation.CityTown;
                TextBoxCounty.Text = organisation.County;
                CheckBoxPreferredOrganization.Checked = organisation.PreferredOrganization != null
                                                            ? organisation.PreferredOrganization.Value
                                                            : false;
                TextBoxTypeOfBusiness.Text = organisation.BusinessType.BusinessName;
                TextBoxSicCode.Text = organisation.BusinessType.SICCode;
                TextBoxPhoneNumber.Text = organisation.PhoneNumber;
                TextBoxFax.Text = organisation.Fax;
                TextBoxEmail.Text = organisation.Email;
                TextBoxWebAddress.Text = organisation.WebAddress;
                TextBoxCharityNumber.Text = organisation.CharityNumber;
                TextBoxCompanyNumber.Text = organisation.CompanyNumber;
                //ButtonInactive.CommandName = organisation.IsActive ? "active" : "deactive";
                ButtonInactive.Visible = organisation.IsActive;
                DropDownListNationCounty.SelectedValue = organisation.CountryId;

                HiddenFieldAddressId.Value = organisation.AddressId.ToString(CultureInfo.CurrentCulture);
                HiddenFieldBusinessId.Value = organisation.BusinessId.ToString(CultureInfo.CurrentCulture);
                HiddenFieldContactId.Value = organisation.ContactId.ToString();
                HiddenFieldOrganizationId.Value = organisation.OrganizationId.ToString(CultureInfo.CurrentCulture);
                HiddenFieldOrganizationName.Value = organisation.OrganizationName;

                string[] specialism = (organisation.OrganizationSpecialism ?? string.Empty).Split('-');
                string[] disabilities = (organisation.ServiceDisabilities ?? string.Empty).Split('-');
                string[] barriers = (organisation.ServiceBarriers ?? string.Empty).Split('-');
                string[] benefits = (organisation.ServiceBenefits ?? string.Empty).Split('-');
                string[] circumstances = (organisation.ServiceCircumstances ?? string.Empty).Split('-');
                string[] ethnicity = (organisation.ServiceEthnicity ?? string.Empty).Split('-');
                string[] accreditation = (organisation.Accreditation ?? string.Empty).Split('-');

                SetSelectedItemsInCheckBoxList(specialism, CheckBoxListOrgSpecial);
                SetSelectedItemsInCheckBoxList(disabilities, CheckBoxListDisabilities);
                SetSelectedItemsInCheckBoxList(barriers, CheckBoxListBarriers);
                SetSelectedItemsInCheckBoxList(benefits, CheckBoxListBenefits);
                SetSelectedItemsInCheckBoxList(circumstances, CheckBoxListCircumstances);
                SetSelectedItemsInCheckBoxList(ethnicity, CheckBoxListEthnicity);
                SetSelectedItemsInCheckBoxList(accreditation, CheckBoxListAccreditation);

                ButtonSave.CommandName = "edit";

                LinkDetails04.Visible = true;
                DetailsPanel04.Visible = true;
            }
        }

        /// <summary>
        /// Loads the Organization programs.
        /// </summary>
        private void LoadOrganisationPrograms()
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganizationId.Value, out organisationId))
            {
                List<int> data =
                    OrganizationBO.GetOrganizationProgramByOrganizationId(organisationId).Select(o => o.ProgramId).
                        ToList();
                if (data.Count <= 0)
                {
                    return;
                }

                CheckBoxInterest.Checked = true;
                LinkDetails03.Visible = true;
                DetailsPanel03.Visible = true;
                LoadExpressionOfInterest();

                foreach (ListItem item in CheckBoxListPrograms.Items)
                {
                    if (data.Contains(int.Parse(item.Value, CultureInfo.CurrentCulture)))
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        /// <summary>
        /// Loads the countries.
        /// </summary>
        private void LoadCountries()
        {
            DropDownListNationCounty.DataSource = CountryBO.SelectCountries();
            DropDownListNationCounty.DataBind();
        }

        /// <summary>
        /// Loads the reference data.
        /// </summary>
        private void LoadReferenceData()
        {
            CheckBoxListOrgSpecial.DataSource = OrganizationBO.GetReferencesByCategoryId(1);
            CheckBoxListOrgSpecial.DataBind();

            CheckBoxListDisabilities.DataSource = OrganizationBO.GetReferencesByCategoryId(2);
            CheckBoxListDisabilities.DataBind();

            CheckBoxListBarriers.DataSource = OrganizationBO.GetReferencesByCategoryId(3);
            CheckBoxListBarriers.DataBind();

            CheckBoxListBenefits.DataSource = OrganizationBO.GetReferencesByCategoryId(4);
            CheckBoxListBenefits.DataBind();

            CheckBoxListCircumstances.DataSource = OrganizationBO.GetReferencesByCategoryId(5);
            CheckBoxListCircumstances.DataBind();

            CheckBoxListEthnicity.DataSource = OrganizationBO.GetReferencesByCategoryId(6);
            CheckBoxListEthnicity.DataBind();

            CheckBoxListAccreditation.DataSource = OrganizationBO.GetReferencesByCategoryId(7);
            CheckBoxListAccreditation.DataBind();
        }

        /// <summary>
        /// Loads the expression of interest.
        /// </summary>
        private void LoadExpressionOfInterest()
        {
            var programBo = new ProgramBO();
            CheckBoxListPrograms.DataSource = programBo.GetProgramList(null, null, -1, -1);
            CheckBoxListPrograms.DataBind();
        }

        /// <summary>
        /// Inits the default control value.
        /// </summary>
        private void InitPostBackControlValues()
        {
            LabelNameExists.Text = string.Empty;
        }

        /// <summary>
        /// Sets the selected items in check box list.
        /// </summary>
        /// <param name="selectedIds">The selected ids.</param>
        /// <param name="checkBoxList">The check box list.</param>
        private static void SetSelectedItemsInCheckBoxList(string[] selectedIds, CheckBoxList checkBoxList)
        {
            foreach (ListItem item in checkBoxList.Items)
            {
                if (selectedIds.Contains(item.Value))
                {
                    item.Selected = true;
                }
            }
        }

        #endregion      
    }
}